package com.alliky.home.repo

import android.content.Context
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.alliky.core.base.BaseRepository
import com.alliky.core.data.DataRepository
import com.alliky.core.data.db.AppDatabase
import com.alliky.core.data.mediator.CategoryRemoteMediator
import com.alliky.core.data.mediator.GoodsRemoteMediator
import com.alliky.core.net.StateLiveData
import com.rrc.common.entity.BannerVO
import com.rrc.common.entity.CategoryVO
import com.rrc.common.entity.GoodsVO
import kotlinx.coroutines.flow.Flow
import java.util.HashMap

/**
 * ================================================
 * @Description: 描述
 * @Author: wxianing
 * @Date: 2023/10/23 18:30
 * ================================================
 */
@ExperimentalPagingApi
class HomeRepo : BaseRepository(){
    companion object {
        private const val PAGE_SIZE = 8
        val config = PagingConfig(
            pageSize = PAGE_SIZE,//每页容量
            initialLoadSize = PAGE_SIZE * 3,//初始加载数量, 默认 = pageSize * 3
            prefetchDistance = PAGE_SIZE,//Paging能无限滚动就是因为它. 当RecycleView 滑动到底部时, 会自动加载下一页. 如果能提前预加载, 可以省去等待加载的步骤. prefetchDistance 就是触发加载的距离底部距离. 默认 = pageSize; 设置 0 时将不会加载更多
            enablePlaceholders = false,//允许使用占位符
            maxSize = PAGE_SIZE * 3
        )
    }

    suspend fun getBanner(
        type: String,
        bannerLiveData: StateLiveData<List<BannerVO>>,
        context: Context,
    ) {
        executeResp({ service.getBanner(type) }, bannerLiveData, context)
    }

    fun getHotGoods(): Flow<PagingData<GoodsVO>> {
        return Pager(
            config = DataRepository.config,
            remoteMediator = GoodsRemoteMediator(service, AppDatabase.get())
        ) {
            AppDatabase.get().goodsDao().queryAllGoods()
        }.flow
    }

    suspend fun getCategoryData(
        hashMap: HashMap<String, String>,
        categoryListLiveData: StateLiveData<List<CategoryVO>>
    ) {
        executeResp({ service.getCategory(hashMap) }, categoryListLiveData)
    }

    fun getCategoryData2(): Flow<PagingData<CategoryVO>> {
        return Pager(
            config = DataRepository.config,
            remoteMediator = CategoryRemoteMediator(service, db)
        ) {
            AppDatabase.get().categoryDao().queryAll()
        }.flow
    }
}